define(function(require, exports, module) {
    'use strict';

    var rk = require('rk');
    // require('commonjs');





    $.widget('rk.approvalContentCtrl', $.rk.oaContentCtrl, {
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            me._initApprovalDetail();
        },
        _init: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
        },
        _initApprovalDetail: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var url = '/json/oa_approval/detail.action';
            rk.post(url, {
                applyId: opt.applyId
            }).done(function(json) {
                if (json.status == 0) {
                    if (json.data.apply.approvers.length > 0) {
                        json.data.apply.hasApprovers = 1;
                        json.data.apply.approversLength = json.data.apply.approvers.length;
                    } else {
                        json.data.apply.hasApprovers = 0;
                    }
                    me._renderDetailContent(json.data);
                    me._bindHandler(json.data);
                    if (json.data.invalidApply == 1) {
                        me._autoReject(json.data.apply.belongId);
                    }
                } else if (json.status == 300002) {
                    var html = rk.templateText(require('oa/tmpl/approval/tpl_approval_content_default_detail.tpl'), {
                        noticeError: rk.i18n('APPROVAL_NOT_EXIST')
                    });
                    elem.html(html);
                } else {
                    var html = rk.templateText(require('oa/tmpl/approval/tpl_approval_content_default_detail.tpl'), {
                        noticeError: rk.i18n('LOAD_ERROR')
                    });
                    elem.html(html);
                }
            });
        },
        _renderDetailContent: function(data) {
            var me = this;
            var elem = me.element;
            var t = data.apply;
            $.each(data.items, function(i, item) {
                var itemValue = '';
                // 1:文本型 2:文本区型 3:单一选择型(下拉,radio) 4:多项选择型 5:整数型 6:实数型 7:日期
                if (item.itemTypeEntry == 7 && item.dateMode == 1) {
                    itemValue = t[item.entryPropertyNameOnly] ? moment(t[item.entryPropertyNameOnly] - 0).format('YYYY-MM-DD') : itemValue;
                } else if (item.itemTypeEntry == 7 && item.dateMode == 2) {
                    itemValue = t[item.entryPropertyNameOnly] ? moment(t[item.entryPropertyNameOnly] - 0).format('YYYY-MM-DD HH:mm') : itemValue;
                } else if (item.itemTypeEntry == 3) {
                    itemValue = (t[item.entryPropertyNameOnly] && item.values[t[item.entryPropertyNameOnly]]) ? $.htmlEncode(item.values[t[item.entryPropertyNameOnly]].name) : itemValue;
                } else if (item.itemTypeEntry == 4) {
                    itemValue = (t[item.entryPropertyNameOnly].length > 0) ? $.map(t[item.entryPropertyNameOnly], function(o, i2) {
                        return $.htmlEncode(item.values[o].name);
                    }).join(',') : itemValue;
                } else if (item.itemTypeEntry == 2) {
                    itemValue = t[item.entryPropertyNameOnly] ? $.htmlEncode(t[item.entryPropertyNameOnly]).replace(/\n/g, '<br>') : itemValue;
                } else {
                    itemValue = t[item.entryPropertyNameOnly] ? $.htmlEncode(t[item.entryPropertyNameOnly]) : itemValue;
                }
                item.itemValue = itemValue;
            });
            $.each(data.users, function(i, o) {
                if (o.icon == '') {
                    o.icon = DEFAULTS.USER_DEFAULT_ICON;
                }
            });
            if (data.apply.approvers.length > 0) {
                $.each(data.apply.approvers, function(i, o) {
                    if (o.icon == '') {
                        o.icon = DEFAULTS.USER_DEFAULT_ICON;
                    }
                });
            }
            var html = rk.templateText(require('oa/tmpl/approval/tpl_approval_content_detail.tpl'), data);
            elem.html(html);
        },
        _bindHandler: function(data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            $('div[_id="approvalResultRadio"]').buttonset();
            elem.on('click', '#cancelBtn', function() {
                me._handleCancelClick();
            });
            elem.on('click', '#showApplyUpdate', function() {
                me._handleUpdateClick();
            });
            elem.on('click', '#deleteApply', function() {
                me._handleDeleteClick();
            });
            elem.on('click', 'input[name="approvalResult_radio"]', function() {
                if ($(this).val() == 1) {
                    var obj = $(this).parents('form.comment_form_approval');
                    obj.find('.nc_reject_show,.nc_comment_show').hide();
                    obj.find('.nc_agree_show').show()
                } else if ($(this).val() == 0) {
                    var obj = $(this).parents('form.comment_form_approval');
                    obj.find('.nc_agree_show,.nc_comment_show').hide();
                    obj.find('.nc_reject_show').show()
                }
            });
            elem.on('focus', '#commentContent', function() {
                $(this).addClass('actived');
            });
            elem.on('click', '#approverSelectNextA', function() {
                me._handleApproverSelectClick($(this));
            });
            if (data.apply.defaultUserName) {
                $("#approverSelectNextA").beTip({
                    dir: 'bottom',
                    closeDelay: false
                })
            }
            elem.on('click', '#showApprovalUserA', function() {
                $('div.nc_show_approval_user').hide();
            });
            elem.on('click', 'a[result]', function() {
                me._handleSubmitApprovalByResultClick($(this));
            });
            elem.find('span[class=approval-tip]').beTip({
                dir: 'bottom',
                closeDelay: false
            });
            elem.on('mouseover', '[_id="approval_process_list"]', function() {
                clearTimeout(me.timer);
                var _this = $(this);
                if (_this.hasClass('check_process')) {
                    $('div[_id="approval_process_list"]').find('.approval_process_list').beScroll();
                    $('div[_id="approval_process_list"]').find('.approval_process_list').beScrollTo('bottom');
                }
                $('div[_id="approval_process_list"]').show();
            });

            elem.on('mouseout', '[_id="approval_process_list"]', function() {
                me.timer = setTimeout(function() {
                    $('div[_id="approval_process_list"]').hide();
                }, 300);
            });
            $("#commentContent").autoTextarea({
                minHeight: 40,
                maxHeight: 600
            });
            elem.on('click', '#showAllFile', function() {
                $('#fileFieldContentDiv div.document_item').show();
                $(this).hide();
            });
            //模版打印用
            elem.on('click', '[act=template_print_select]', function() {
                elem.find("[act=template_print_select_option]").toggle();
            });
            elem.on('click', '[act=template_print_select_one]', function() {
                var template_print_select_one = $(this);
                location.href = template_print_select_one.attr("href");
            });
            elem.on('click', '[act=template_print_select_option_a]', function() {
                elem.find("[act=template_print_select_option]").hide();
            });
            var $detail = elem.find('div.task_right_detail_inner');
            $detail.simpleTabs({
                active: -1,
                tabContainer: 'div.approval_detail_bottom',
                tabsElement: 'ul li.jstab',
                tabsHolder: 'ul li.jstab a',
                panelsElement: '>div.bottom_tabs_content >div',
                activate: function(index, $tab, $panel, force) {
                    if ($panel.data('inited') == true && !force) {
                        return;
                    }
                    switch (index) {
                        case 1:
                            rk.post('/json/oa_approval/logs.action', {
                                applyId: data.apply.applyId
                            }).done(function(json) {
                                if (json.status == 0) {
                                    var _data = json.data,
                                        logs = _data.logs;
                                    var html = $.map(logs, function(log) {
                                        var opid = log.userId,
                                            opname = _data.users[opid].name,
                                            opicon = _data.users[opid].icon || DEFAULTS.USER_DEFAULT_ICON,
                                            msg = '';
                                        switch (log.operateType) {
                                            case 1:
                                                msg = rk.i18n('APPROVAL_OPERATE_SUBMIT');
                                                break;
                                            case 2:
                                                msg = rk.i18n('APPROVAL_OPERATE_UPDATE');
                                                break;
                                            case 3:
                                                msg = rk.i18n('APPROVAL_OPERATE_RESUBMIT');
                                                break;
                                            case 4:
                                                msg = [rk.i18n('APPROVAL_OPERATE_REJECT') + '“', log.opinion, '”'].join('');
                                                break;
                                            case 5:
                                                msg = rk.i18n('APPROVAL_OPERATE_CANCEL');
                                                break;
                                            case 6:
                                                msg = rk.i18n('APPROVAL_OPERATE_AGREE');
                                                break;
                                            case 7:
                                                msg = rk.i18n('APPROVAL_OPERATE_PASS');
                                                break;
                                            default:
                                                msg = rk.i18n('APPROVAL_WAIT');
                                                break;
                                        }
                                        return ['<div class="comment_content clear"><img class="userlogo" src="', opicon, '"><div class="right_comment"><div class="comment_word"><span><a target="_blank" href="/final/user.action?uid=', opid, '" class="username">', opname, '</a></span><span> ', msg, '</span></div><div class="show_tool"><a class="publish_time">', log.createdAt, '</a></div></div></div>'].join('');
                                    }).join('');
                                    $panel.find('div.show_comment').html(html);
                                    $panel.data('inited', true);
                                }
                            });
                            break;
                    }
                }
            });
            $detail.simpleTabs('selectTab', 0);
            $detail.find('div.js-comments').comment({
                previewList: data.comments, //预展示列表
                totalCount: data.commentCount, //总条数
                canAt: 1,
                canReply: 1,
                systemId: 602,
                systemItemId: data.apply.applyId,
                allusers: data.users //若有previewList,需要把对应的user对象放进来
            });
        },
        _autoReject: function(belongId) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            rk.alert((belongId == 1 ? rk.i18n('APPROVAL_THIS_ACCOUNT') : rk.i18n('APPROVAL_THIS_LEAD')) + rk.i18n('APPROVAL_ALERT_CONTENT'), function() {
                rk.post('/json/oa_approval/deal-approval.action', {
                    commentSystemItemId: opt.applyId,
                    approvalResult: 0,
                    commentContent: rk.i18n('APPROVAL_AUTO_REJECT_CONTENT')
                }).done(function(json) {
                    if (json.status == 0) {
                        if ($("#oa_content").length == 0) { //最终页刷新当前页面
                            window.top.location.reload();
                        } else {
                            $("div.oa-tab-header a.active").click();
                            rk.oa.closeContent();
                        }
                        $.msg(rk.i18n('OPERATE_SUCCESS'), 1);
                    } else {
                        $.msg(rk.i18n('OPERATE_LOSE'));
                    }
                });
            });
        },
        _handleCancelClick: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            rk.confirm(rk.i18n('APPROVAL_CANCEL_CONFIRM'), function() {
                var url = '/json/oa_approval/cancel.action';
                rk.post(url, {
                    applyId: opt.applyId
                }).done(function(json) {
                    if (json.status == 0) {
                        if ($("#oa_content").length == 0) { //最终页刷新当前页面
                            window.top.location.reload();
                        } else {
                            $("div.oa-tab-header a.active").click();
                            me.closeMe();
                        }
                        $.msg(rk.i18n('OPERATE_SUCCESS'), 1);
                    } else {
                        $.msg(rk.i18n('OPERATE_LOSE'));
                    }
                });
            });
        },
        _handleUpdateClick: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            rk.dialog({
                title: rk.i18n('APPROVAL_UPDATE_TITLE'),
                success: function(dialogElem) {
                    dialogElem.updateApprovalDialogCtrl({
                        applyId: opt.applyId
                    });
                },
                footer: [{
                    act: 'cancelUpdate',
                    color: 'white',
                    visible: true,
                    text: rk.i18n('CANCEL')
                }, {
                    act: 'updateApproval',
                    visible: true,
                    text: rk.i18n('APPROVAL_NEXT_STEP')
                }]
            });
        },
        _handleDeleteClick: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            rk.confirm(rk.i18n('APPROVAL_DELETE_CONFIRM'), function() {
                var url = '/json/oa_approval/delete.action';
                rk.post(url, {
                    applyId: opt.applyId
                }).done(function(json) {
                    if (json.status == 0) {
                        if ($("#oa_content").length == 0) { //最终页刷新当前页面
                            window.top.location.reload();
                        } else {
                            $("div.oa-tab-header a.active").click();
                            me.closeMe();
                        }
                        $.msg(rk.i18n('OPERATE_SUCCESS'), 1);
                    } else {
                        $.msg(rk.i18n('OPERATE_LOSE'));
                    }
                });
            });
        },
        _handleApproverSelectClick: function(selectAObj) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var formContainer = $(selectAObj).parents("form.comment_form_approval");
            var userSelect = formContainer.find("#approvalUserSelect");
            var approvalUser_hidden = formContainer.find(":hidden.approvalUser_hidden");
            var select_depart_list = formContainer.find("div.select_depart_list");
            var nc_selectColleague_li = select_depart_list.find(".nc_selectColleague_li");
            userSelect.rkUser({
                onSelect: function(userId, userName) {
                    $(selectAObj).text(userName);
                    approvalUser_hidden.val(userId);
                    select_depart_list.hide();
                }
            });
            nc_selectColleague_li.bind("click", function() {
                var approval = $(this).attr("uname");
                approvalUser_hidden.val($(this).attr("uid"));
                $(selectAObj).text(approval);
                select_depart_list.hide();
            });
            if (!select_depart_list.is(":hidden")) {
                select_depart_list.hide();
            } else if (nc_selectColleague_li.size() > 0 || userSelect.size() > 0) {
                select_depart_list.show();
            }
        },
        _handleSubmitApprovalByResultClick: function(aObj) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var result = $(aObj).attr('result');
            var formObj = $(aObj).parents("form.comment_form_approval");
            var isCounterSigner = formObj.find(":hidden.isCounterSigner").val();
            formObj.find(":hidden.approvalResult").val(result);
            var approvalUserHidden = formObj.find(":hidden.approvalUser_hidden");
            var taEle = formObj.find("textarea.approval_textarea");
            if ($.trim(taEle.val()).length > 800) {
                $.msg(rk.i18n('APPROVAL_SUBMIT_FORM_ERROR_1'));
                return false;
            }
            if (result < 0) { //补充意见
                if ($.trim(taEle.val()) == "") {
                    $.msg(rk.i18n('APPROVAL_SUBMIT_FORM_ERROR_2'));
                    return false;
                }
                me._handleSubmitApprovalClick(result, formObj);
                return false;
            } else if (result == 0) {
                if ($.trim(taEle.val()) == "") {
                    $.msg(rk.i18n('APPROVAL_SUBMIT_FORM_ERROR_2'));
                    return false;
                }
            } else if (result == 1 && approvalUserHidden.length > 0) {
                if (approvalUserHidden.val() == "") {
                    $.msg(rk.i18n('APPROVAL_SUBMIT_FORM_ERROR_3'));
                    return false;
                }
            }
            var confirmMsg = (result == 1 ? rk.i18n('APPROVAL_SUBMIT_FORM_CONFIRM_1') : isCounterSigner > 0 ? rk.i18n('APPROVAL_SUBMIT_FORM_CONFIRM_3') : rk.i18n('APPROVAL_SUBMIT_FORM_CONFIRM_2'));
            rk.confirm(confirmMsg, function() {
                me._handleSubmitApprovalClick(result, formObj);
            });
        },
        _handleSubmitApprovalClick: function(result, formObj) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var loadEle = formObj.find(".green_button:visible");
            var options = {
                iframe: false,
                resetForm: true,
                beforeSubmit: function() {
                    //l.start();
                },
                success: function(responseText) {
                    var responseTextJson = responseText; //$.evalJSON(responseText);
                    var status = responseTextJson.status;
                    var statusText = responseTextJson.statusText;
                    if (status == 0) {
                        $.msg(rk.i18n('OPERATE_SUCCESS'), 1);
                        if ($("#oa_content").length == 0) { //最终页刷新当前页面
                            window.top.location.reload();
                        } else {
                            $("div.oa-tab-header a.active").click();
                            me.closeMe();
                        }
                    } else if (status == 213006) {
                        $.msg(rk.i18n('APPROVAL_SUBMIT_CONFIRM_ERROR_CONTENT'));
                    } else {
                        $.msg(statusText);
                    }
                    //l.stop();
                }
            };
            formObj.ajaxSubmit(options);
        }
    });

    return {
        init: function(rkContent, id) {
            rkContent.approvalContentCtrl({
                applyId: id
            });
        }
    }
});
